package com.xnet.shiro.controller.base;

import com.xnet.common.annotation.SysLog;
import com.xnet.common.constant.SystemConstant;
import com.xnet.common.controller.AbstractController;
import com.xnet.common.entity.Page;
import com.xnet.common.entity.R;
import com.xnet.common.entity.TreeEntity;
import com.xnet.common.entity.UserEntity;
import com.xnet.common.utils.TreeNodeUtils;
import com.xnet.shiro.service.base.DepartmentService;
import com.xnet.shiro.service.base.OrganizeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xnet.shiro.service.base.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author Xingyc
 * @date 2018-1-8 12:00:47
 */
@Api(value = "/user", tags = "User接口")
@RestController
@RequestMapping("/sys/user")
public class UserController extends AbstractController {

    @Autowired
    private UserService userService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private OrganizeService organizeService;

    /**
     * 用户列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public Page<UserEntity> list(@RequestBody Map<String, Object> params) {

        if (!getUserAccount().equals(SystemConstant.IS_ADMIN)) {
            params.put("createUserId", getUserId());
        }
        return userService.listUser(params);
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public R info() {

        return R.ok().put("user", getUser());
    }

    /**
     * 用户权限
     *
     * @return
     */
    @RequestMapping("/perms")
    public R listUserPerms() {

        return userService.listUserPerms(getUserId());
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @SysLog("新增用户")
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user) {
        userService.create(user);
        return userService.saveUser(user);
    }

    /**
     * 根据id查询详情
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "根据id获取用户信息", notes = "根据id获取用户信息", httpMethod = "GET", response = R.class)
    @RequestMapping("/infoUser")
    public R getById(@RequestBody String userId) {

        return userService.getUserById(userId);
    }

    /**
     * 根据部门id获取用户列表
     *
     * @param departmentId
     * @return 用户列表
     */
    @RequestMapping("/departmentUser")
    public List<UserEntity> getListByDepartmentId(String departmentId) {

        return userService.getListByDepartmentId(departmentId);

    }

    /**
     * 系统管理员校验
     * @param userId
     * @return
     */
    private R CheckIsAdmin(String userId) {

        if (userId.equals(SystemConstant.IS_ADMIN)) {
            return R.error(500, "系统管理账号，禁止此操作！");
        }
        return null;
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @SysLog("修改用户")
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user) {
        R result = CheckIsAdmin(user.getUserId());
        return result == null ? userService.updateUser(user) : result;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @SysLog("删除用户")
    @RequestMapping("/remove")
    public R batchRemove(@RequestBody String[] id) {
        R result = CheckIsAdmin(id[0]);
        return result == null ? userService.batchRemove(id) : result;
    }

    /**
     * 用户修改密码
     *
     * @param password
     * @param newPassword
     * @return
     */
    @SysLog("修改密码")
    @RequestMapping("/updatePswd")
    public R updatePswdByUser(String password, String newPassword) {

        UserEntity user = getUser();
        user.setPassword(password);//原密码
        user.setEmail(newPassword);//邮箱临时存储新密码
        return userService.updatePswdByUser(user);
    }

    /**
     * 启用账户
     *
     * @param id
     * @return
     */
    @SysLog("启用账户")
    @RequestMapping("/enable")
    public R updateUserEnable(@RequestBody String[] id) {
        R result = CheckIsAdmin(id[0]);
        return result == null ? userService.updateUserEnable(id) : result;
    }

    /**
     * 禁用账户
     *
     * @param id
     * @return
     */
    @SysLog("禁用账户")
    @RequestMapping("/disable")
    public R updateUserDisable(@RequestBody String[] id) {
        R result = CheckIsAdmin(id[0]);
        return result == null ? userService.updateUserDisable(id) : result;
    }

    /**
     * 重置密码
     *
     * @param user
     * @return
     */
    @SysLog("重置密码")
    @RequestMapping("/reset")
    public R updatePswd(@RequestBody UserEntity user) {
        R result = CheckIsAdmin(user.getUserId());
        return result == null ? userService.updatePswd(user) : result;
    }


    /**
     * 获取机构+部门树+用户
     *
     * @param keyword
     * @return
     */
    @RequestMapping("/getOrgDeptUserTree")
    public List<TreeEntity> getOrganizeDepartmentUserTreelist(String keyword) {

        List<TreeEntity> allUserTreeList = userService.getOrganizeDepartmentUserTreelist();
        //获取关联追溯后的树形列表
        List<TreeEntity> relationTreeList = new ArrayList<>();

        if (keyword != null && !keyword.isEmpty()) {
            //执行检索过滤 获取过滤后的树形列表
            List<TreeEntity> filterTreeList = new ArrayList<>();
            filterTreeList = allUserTreeList.stream().filter(x -> x.getText() != null && x.getText().contains(keyword)).collect(Collectors.toList());
            //获取符合过滤条件的所有节点链条（向上追溯）
            TreeNodeUtils.getWholeTreeChain(allUserTreeList, filterTreeList, relationTreeList);

        } else {
            relationTreeList = allUserTreeList;
        }

        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(relationTreeList, "0", newTreeList);
        return newTreeList;
    }

}
